package com.liu;

import com.liu.springmvc.servlet.LiuDispatcherServlet;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

/**
 * @author LIU
 * @version 1.0
 * @date 2024/1/24 11:48
 * @description TODO
 * 1. tomcat启动
 * 2. 创建servlet对象
 * 3. init()-------创建spring容器-----onRefresh()初始化servlet
 * 4. 从spring容器中拿到handlerMapping实现类
 *      BeanNameUrlHandlerMapping映射
 *      requestMapping请求映射
 *
 */
public class Application {
    public static void main(String[] args) {
        startTomcat();
    }


    private static void startTomcat() {
        Tomcat tomcat = new Tomcat();
        StandardContext context = new StandardContext();

        String contextPath = "";
        context.setPath(contextPath);  // 容器上下文
        context.addLifecycleListener(new Tomcat.FixContextListener());

        StandardHost host = new StandardHost();
        host.setName("localhost");
        host.addChild(context);

        StandardEngine engine = new StandardEngine();
        engine.setDefaultHost("localhost");
        engine.addChild(host);

        Connector connector = new Connector();
        connector.setPort(8081);

        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");
        service.setContainer(engine);
        service.addConnector(connector);

        // tomcat是servlet容器
        // 每一个servlet都有自己的applicationContext
        // web.xml配置
        tomcat.addServlet(contextPath,"dispatcher",new LiuDispatcherServlet());
        context.addServletMappingDecoded("/","dispatcher");


        try {
            tomcat.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
